package com.zhuhjay.chat.client.handler;

import com.zhuhjay.chat.message.LoginResponseMessage;
import io.netty.channel.ChannelHandlerContext;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 登录响应消息处理器
 * @author ZhuHJay
 * @date 2023/3/9 11:20
 */
public class LoginResponseMessageHandler extends AbstractResponseMessageHandler<LoginResponseMessage> {
    private CountDownLatch latch = new CountDownLatch(1);
    private final AtomicBoolean login = new AtomicBoolean();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginResponseMessage msg) throws Exception {
        if (msg.isSuccess()) {
            login.set(true);
            System.out.printf("\rTIP: %s%n", msg.getReason());
        } else {
            System.out.printf("\rERROR: %s%n", msg.getReason());
        }
        latch.countDown();
    }

    /** 是否登录 */
    public boolean isLogin() {
        return login.get();
    }

    /** 同步等待 */
    public void await() throws InterruptedException {
        latch.await();
        // 重置计数等待
        latch = new CountDownLatch(1);
    }
}
